package com.sifa.springcloud.controller;


import com.sifa.springcloud.entities.CommentResult;
import com.sifa.springcloud.entities.Payment;
import com.sifa.springcloud.service.PaymentService;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
public class PaymentController {

    @Resource
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    @Resource
    private DiscoveryClient discoveryClient;


    @PostMapping("/payment/create")
    public CommentResult createPayment(@RequestBody Payment payment){

        System.out.println("对了吗");
        int i = paymentService.create(payment);
        if (i>0){
            return new CommentResult(200,"插入数据库成功"+serverPort,null);
        }
        return new CommentResult(404,"插入失败",null);
    }
    @GetMapping("/payment/get/{id}")
    public CommentResult getPayment(@PathVariable("id")Integer id){
        Payment paymentById = paymentService.getPaymentById(id);
        if (paymentById!=null){
            return new CommentResult(0,"成功"+serverPort,paymentById);
        }
      else {
          return new CommentResult(0,"失败",null);
        }
    }
    @GetMapping("/payment/discovery")
    public Object getDiscoverClient(){
        //获得服务信息，导入的包是springCloud的
        List<String> services = discoveryClient.getServices();
        for (int i = 0; i < services.size(); i++) {
            System.out.println(services.get(i));
        }
        //获得一个微服务名字下面的所有实例
        List<ServiceInstance> instances = discoveryClient.getInstances("cloud-payment-service");
        for (ServiceInstance instance : instances) {
            System.out.println("服务id"+instance.getServiceId()+
                    "服务端口号"+instance.getPort()+"服务访问地址"
                    +instance.getUri()
            );
        }
        return this.discoveryClient;
    }
    @GetMapping("/payment/lb")
    public String getPaymentLB(){
        return serverPort;
    }
}
